package com.ns.dcjh.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Environment;

import com.ns.dcjh.MyApplication;
import com.ns.dcjh.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class FileUtils {

    @SuppressLint("DefaultLocale")
    public static File getFile(String prefix, String suffix) {
        Random random = new Random();
        String fileName = String.format("%s_%d_%d.%s", prefix, System.currentTimeMillis(), random.nextInt(1000), suffix);
        String appName = MyApplication.getInstance().getString(R.string.app_name);
        String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + appName;
        if (Build.VERSION.SDK_INT > 29) {
            dir = MyApplication.getInstance().getExternalFilesDir(null).getAbsolutePath() + File.separator + appName;
        }
        isExist(dir);
        return new File(dir, fileName);
    }

    //判断文件夹是否存在,如果不存在则创建文件夹
    public static void isExist(String path) {
        File file = new File(path);

        if (!file.exists()) {
            file.mkdir();
        }
    }


    public static String getAssetsJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

}
